package net.fireox.oa.comm.rtc.service.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.AsyncContext;

import net.fireox.oa.comm.rtc.entity.RTCMessage;
import net.fireox.oa.comm.rtc.service.RTCService;
import net.fireox.oa.comm.rtc.store.RTCConnectionStore;
import net.fireox.oa.comm.rtc.store.RTCMessageStore;
import net.fireox.oa.util.json.JsonUtil;

import org.springframework.stereotype.Repository;

@Repository(value="rtcService")
public class RTCServiceImpl implements RTCService 
{

	public static final String RTC_MESSAGE_STORE = "RTC_MESSAGE_STORE";
	
	@Override
	public void sendMessage(RTCMessage msg) {
		// TODO Auto-generated method stub
		
		RTCMessageStore.putMessage(msg);
		
		this.processMessage(msg.getReciever());
	}

	@Override
	public void sendMessage(List<RTCMessage> msgs) {
		// TODO Auto-generated method stub
		for(RTCMessage msg : msgs){
			RTCMessageStore.putMessage(msg);
			this.processMessage(msg.getReciever());
		}
	}
	
	protected void persistMessage(){
		
	}
	
	protected void processMessage(String key){
		
		AsyncContext context = RTCConnectionStore.poll(key);
		
		if(context!=null){
			List<RTCMessage> msgs = RTCMessageStore.getMessages(key);
			
			try {
				PrintWriter out = context.getResponse().getWriter();
				
				out.print(JsonUtil.encode(msgs));
				out.flush();
				
				context.complete();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
